import { Message } from 'element-ui'
import SocketPlugin from '@/utils/webSocket.js'

export default class getPrinterList {
  constructor(cb) {
    // 平台类型对应的webSocket端口
    this.printClien = [
      { value: 'ws://localhost:13528', label: 'CAINIAO' },
      { value: 'ws://localhost:5000', label: 'PDD' },
      { value: 'ws://localhost:13888', label: 'DY' },
      { value: 'ws://localhost:9113', label: 'JD' }
    ]
    this.type = 'CAINIAO' // 当前使用的平台
    this.defaultPrinter = '' // 默认打印机名
    this.cb = cb // Function  选传  打印成功后执行的回调
  }

  initSocket() {
    // 初始化
    this.ws = new SocketPlugin({
      url: this.printClien[0].value,
      received: (data) => {
        // 监听服务器返回信息
        if (typeof data === 'object') {
          if (this.printClien.length === 1) {
            Message.close()
            Message.error({ message: '获取打印机列表失败！请打开 <菜鸟、抖音、京东、拼多多> 任一打印客户端后刷新页面重试！' })
            this.cb && this.cb({ status: 500 })
          } else {
            this.changeType()
          }
        } else {
          this._receiveMessage(this._msgHandler(data))
        }
      }
    })

    this._getPrinters()
  }

  // 建立连接，并下发获取打印机列表命令
  _getPrinters() {
    let sendData = {
      cmd: 'getPrinters',
      requestID: new Date().getTime().toString(),
      version: '1.0'
    }
    if (this.type === 'JD') {
      sendData = {
        orderType: 'GET_Printers',
        pin: '用户名',
        parameters: {
          tempUrl: '',
          printName: '',
          printData: ''
        }
      }
    }
    this.ws.connect(sendData)
  }
  // 接收到的消息
  _receiveMessage(result) {
    if (this.type === 'JD') {
      if (result.code === '6') {
        // 打印机列表
        this.defaultPrinter = result.content.split(',')[0]
        this.handleCallback(result.detailinfo.printers)
      }
    } else {
      if (result.cmd === 'getPrinters') {
        this.defaultPrinter = result.defaultPrinter
        this.handleCallback(result.printers.map(item => item.name))
      }
    }
  }
  // 处理回调
  handleCallback(list) {
    this.cb && this.cb({ status: 0, list })
  }
  // 更换打印客户端尝试再次获取打印机列表
  changeType() {
    this.printClien.shift()
    if (this.printClien.length > 0) {
      this.type = this.printClien[0].label
      this.initSocket()
    }
  }

  // 返回数据格式化
  _msgHandler(msg) {
    if (msg === void 0) {
      return {}
    } else {
      try {
        return JSON.parse(msg)
      } catch (e) {
        return {}
      }
    }
  }
}
